<?php
require_once('../../libraryfiles/config.php');
$action = isset($_GET['action']) ? $_GET['action'] : '';
switch ($action) {
    case 'add' :
        add();
        break;

    case 'apply' :
        add(true);

    case 'addexist' :
        addexist();
        break;

    case 'delselected' :
        deleteSelected();
        break;

    case 'deletet_count' :
        deletetCount();
        break;

    case 'publish' :
        publishSelected();
        break;

    case 'updatePrice':
        updatePrice();
        break;

    case 'displaypro':
        display();
        break;

    case 'diplayexist':
        displayexit();
        break;

    case 'search_pro':
        search_pro();
        break;

    default :
        // if action is not defined or unknown
        // move to main user page
        header('Location: index.php');
        exit();
}

function applyWaterMark($imagePath, $fileName) {
    $font = '../../fonts/arial.ttf';
    $sql = 'SELECT * FROM ' . Tblrefcode::tblname . ' WHERE ' . Tblrefcode::name . ' = ' . '"watermark"';
    $query = mysql_query($sql);
    $row = mysql_fetch_object($query);
    $text = $row->{Tblrefcode::value};
    generateWatermarkForEachImage($imagePath, $fileName, $text, $font);
}

function add() {

    $ID = $_POST['hidid'];
    $pro_name = ampReplace($_POST['new_proname']);
    $pro_name = addslashes($pro_name);
    $pro_typ = @$_POST['selectType'];
    $pro_version = @$_POST['selectProductVersion'];
    $pro_keywords = @$_POST['txtkeywords'];
    $made_in = @$_POST['selectCoun'];
    $pro_price = $_POST['price'];
    $laboratory = @$_POST['laboratory'];
    $pharmacy_id = $_SESSION['acc_id'];
    $pid = @$_POST['hidpid'];
    $desc = str_replace("'", "'", $_POST['txtdesc']);
    $desc = str_replace("\"../images/", "\"" . W_IMAGES_DIR, $desc);
    $desc = str_replace("\"../../images/", "\"" . W_IMAGES_DIR, $desc);
    $desc = addslashes($desc);
    $selectCate = isset($_POST['selectcat']) ? $_POST['selectcat'] : '';
    $link = $detectExist_q = "";
    $Cont_Name = trim($_POST['txtname']);
    $Cont_Email = trim($_POST['txtemail']);
    $Cont_Tel = trim($_POST['txttelephone']);
    $Cont_Address = trim($_POST['txtaddress']);
    
    if (empty($ID)) {
        if (empty($_POST['new_proname']) || empty($_POST['txtdesc']) || empty($_POST['price']) || empty($_POST['selectcat'])) {
            setSession(array('ProductName' => @$pro_name, 'description' => @$desc, 'KeyWord' => @$pro_keywords, 'Price' => @$pro_price[0], 'Condition' => @$pro_version));
            header("location:" . base_url . "/account/product/index.php?view=add&error=required");
            exit();
        } else {
            clearSession(array('ProductName', 'description', 'KeyWord', 'Price', 'Condition'));
        }
    }
    
    $modify = false;
    if (!empty($ID)) {
        $modify = true;
        $link = "&id=" . $ID;
        $detectExist_q .= " AND id != " . $ID;
    }
    //Statment to detect the entry Lesson Category Name exist
    if (existRecord("tblproduct", "product_name = '$pro_name' $detectExist_q")) {
        header('Location:' . base_url . 'account/product/index.php?view=add' . $link . $qstr . '&error=' . urlencode('Name already taken. Please choose another one'));
        exit();
    } else if ($modify) {
        $update = update(Tblproduct::tblproduct, array(
            Tblproduct::name => $pro_name,
            'product_description' => $desc,
            Tblproduct::keyword => $pro_keywords,
            Tblproduct::product_version => $pro_version,
            'contact_name' => $Cont_Name,
            'contact_email' => $Cont_Email,
            'contact_phone' => $Cont_Tel,
            'contact_address' => $Cont_Address,
            Tblproduct::mdate => date("Y-m-d H:i:s"),
            Tblproduct::type => $pro_typ,
            Tblproduct::owner => $pharmacy_id,
                ), array(Tblproduct::id => $ID));
        $last_id = $ID;

        $sql2 = "DELETE FROM tblproduct_in_category WHERE product_id = $last_id";
        mysql_query($sql2);

        //Pharmacy Query
        foreach ($made_in as $key => $value) {
            $country = $value;
            $price = $pro_price[$key];
            $labor = $laboratory[$key];
            $sql_del = "DELETE FROM tblproduct_in_pharmacy WHERE product_id='" . $ID . "'";
            mysql_query($sql_del);
            $sql_pha = "INSERT INTO tblproduct_in_pharmacy(product_id, pharmacy_id, country_id, price, laboratory, status) VALUES('" . $last_id . "', '" . $pharmacy_id . "', '" . $country . "', '" . $price . "', '$labor',1)";
            mysql_query($sql_pha);
        }
    } else {
        //Ordering number
        $ordering_q = "SELECT MAX(product_ordering) AS ordering
				   FROM tblproduct";
        $ordering_r = mysql_query($ordering_q);
        $ordering_info = mysql_fetch_assoc($ordering_r);
        extract($ordering_info);
        $ordering += 1;
        // Product Query
        $province_id = $_SESSION['province_id'];
        $district_id = $_SESSION['disctict_id'];
        $postType = (($_SESSION['usertype'] == 3) ? 0 : 1);
        $date = date("Y-m-d H:i:s");
        $data_pro = array(
            Tblproduct::name => $pro_name,
            Tblproduct::type => $pro_typ,
            Tblproduct::product_version => $pro_version,
            Tblproduct::keyword => $pro_keywords,
            Tblproduct::cdate => $date,
            Tblproduct::mdate => $date,
            'product_description' => $desc,
            Tblproduct::status => 1,
            Tblproduct::owner => $pharmacy_id,
            Tblproduct::province_id => $province_id,
            Tblproduct::district_id => $district_id,
            Tblproduct::post_type => $postType,
            'contact_name' => $Cont_Name,
            'contact_email' => $Cont_Email,
            'contact_phone' => $Cont_Tel,
            'contact_address' => $Cont_Address
        );
        $last_id = insert(Tblproduct::tblproduct, $data_pro);
        //Pharmacy Query
        
        if (!empty($made_in)) {
            foreach ($made_in as $key => $value) {
                $country = $value;
                $price = $pro_price[$key];
                $labor = $laboratory[$key];
                $sql_pha = "INSERT INTO tblproduct_in_pharmacy(product_id, pharmacy_id, country_id, price, laboratory, status) VALUES('" . $last_id . "', '" . $pharmacy_id . "', '" . $country . "', '" . $price . "', '$labor',1)";
                mysql_query($sql_pha);
            }
        } else {
            $price = $pro_price[$key];
            $sql_pha = "INSERT INTO tblproduct_in_pharmacy(product_id, pharmacy_id, country_id, price, laboratory, status) VALUES('" . $last_id . "', '" . $pharmacy_id . "', '" . $country . ", '" . $price . "', '$labor',1)";
        }
    }

    // Category Query
    $selectCate = isset($_POST['selectcat']) ? $_POST['selectcat'] : '';
    if (!empty($selectCate)) {
        foreach ($selectCate as $value) {
            $sql_cate = "INSERT INTO tblproduct_in_category VALUES('" . $value . "','" . $last_id . "')";
            mysql_query($sql_cate);
        }
    }

    // Insert Image
    $imagefile = $_FILES['imagefile'];
    if(!empty($imagefile)){
    $arrayTemp = array();
    if (!empty($imagefile)) {
        foreach ($imagefile as $index => $name) {

            foreach ($name as $key => $value) {
                $arrayTemp[$key][$index] = $value;
            }
        }
    }
    }
    //print_r($arrayTemp);exit;



    /* insert product image */

    include S_ROOT . '/includefiles/upload_image_options.php';
    
     if (!empty($ID)) {
        if (!empty($_POST['DelImage'])) {
            $images_id = $_POST['DelImage'];
            foreach ($images_id as $image_id) {
                $imgName = mysql_query("SELECT *FROM tblimage WHERE id='" . $image_id . "'");
                $img = mysql_fetch_object($imgName);
                if (!empty($img)) {
                    $fullImage = S_S_IMAGES_DIR . 'thumb/' . $img->images;
                    $thumbImage = S_S_IMAGES_DIR . $img->images;
                    if (file_exists($thumbImage)) {
                        unlink($fullImage);
                        unlink($thumbImage);
                    }
                    $deleteImgQuery = "DELETE FROM tblimage WHERE id='" . $img->id . "'";
                    mysql_query($deleteImgQuery);
                }
            }
        }
     }
    
    if (!empty($arrayTemp)) {
        foreach ($arrayTemp as $newimage) {
            if (!empty($newimage['name'])) {
                $imageName = uploadProductimage($newimage, $resizeWidth, $resizeHeight, $logoPath, $logoPosition);
                if (!empty($imageName)) {
                    $data_img = array(
                        Tblimage::images => $imageName,
                        Tblimage::product_id => $last_id,
                    );
                    $imageInsert = insert(Tblimage::TABLE, $data_img);
                }
            }
        }
    }
    header('Location: ' . base_url . "account/product/?success=PRO_ADD_SUCCESS");
}

function addexist() {
    $id = $_POST['hidnewid'];
    $made_in = $_POST['selectCountry'];
    $pro_price = $_POST['newprice'];
    $pharmacy_id = $_SESSION['acc_id'];
    $laboratory = $_POST['new_laboratory'];
    $pid = $_POST['hidupdate'];
    $link = $detectExist_q = "";
    $modify = false;
    if (!empty($pid)) {
        $modify = true;
        $link = "&id=" . $pid;
        $detectExist_q .= " AND pid != " . $pid;
    }
    // exist record
    foreach ($made_in as $key => $value) {
        $country = $value;
        $price = $pro_price[$key];
        $labor = addslashes($laboratory[$key]);
        $pids = $pid[$key];
        $sql_e = "SELECT * FROM tblproduct_in_pharmacy WHERE product_id = $id AND country_id = $country AND pharmacy_id = $pharmacy_id AND laboratory = '$labor' AND pid!=$pids";
        $result_e = mysql_query($sql_e);
    }
    if (dbNumRows($result_e)) {
        $error = 'You have this product already !';
        header("Location:" . base_url . "account/product/index.php?view=add&error=$error");
        exit();
    } else if ($modify) {
        foreach ($made_in as $key => $value) {
            $country = $value;
            $price = $pro_price[$key];
            $labor = addslashes($laboratory[$key]);
            $pids = $pid[$key];
            $sql_del = "DELETE FROM tblproduct_in_pharmacy WHERE pid=$pids";
            mysql_query($sql_del);
            $sql_pha = "INSERT INTO tblproduct_in_pharmacy(product_id, pharmacy_id, country_id, price, laboratory, status) VALUES($id, $pharmacy_id, $country, '$price', '$labor',1)";
            mysql_query($sql_pha);
        }
    } else {
        //Pharmacy Query
        foreach ($made_in as $key => $value) {
            $country = $value;
            $price = $pro_price[$key];
            $labor = $laboratory[$key];
            $sql_pha = "INSERT INTO tblproduct_in_pharmacy(product_id, pharmacy_id, country_id, price, laboratory, status) VALUES($id, $pharmacy_id, $country, '$price', '$labor',1)";
            mysql_query($sql_pha);
        }
    }
    header("Location:" . base_url . "account/product/index.php");
}

function search_highlight($needle, $replace, $haystack) {
    $haystack = str_replace($needle, $replace, $haystack);
    return $haystack;
}

function search_pro() {
    $pro_name = addslashes($_GET['searchword']);
    $sql = "SELECT * FROM tblproduct WHERE product_name LIKE '$pro_name%' AND status = 1";
    $result = mysql_query($sql);
    if (dbNumRows($result)) {
        echo '<span id="id" style="color:#999;"><em>Search Result...</em></span><br /><br />';
        $i = 1;
        while ($row = mysql_fetch_assoc($result)) {
            $sql_img = "SELECT thumbnail FROM tblimage WHERE product_id = " . $row['id'] . " LIMIT 0,1";
            $result_img = mysql_query($sql_img);
            $row_img = mysql_fetch_assoc($result_img);

            if ($i % 2) {
                $class = 'search_row1';
            } else {
                $class = 'search_row2';
            }
            $i++;
            ?>
            <div style="width: 320px; height: auto;">
                <div style="float: left; width: 70px;"><?php
            if ($row_img['thumbnail'] != "") {
                $thumbnail_i = $row_img['thumbnail'];
            } else {
                $thumbnail_i = 'no-image-small.png';
            }
            ?> <img
                        src="<?php echo W_ROOT; ?>/seller/product/images/<?php echo $thumbnail_i; ?>"
                        class="border" width="70" /></div>
                <div
                    style="float: left; padding-left: 15px; padding-top: 10px; width: 180px;"><strong
                        style="color: #06C;"><?php echo $row['product_name']; ?></strong><br />
                    <em style="color: #666;">( Product type : <?php echo $row['product_type']; ?>
                        )</em></div>
                <div style="float: right; padding-top: 10px;"><a href="#1"
                                                                 id="<?php echo $row['id']; ?>" class="addproduct"><img
                            src="<?php echo W_ROOT; ?>/images/btnadd.jpg" border="0" /></a></div>
            </div>
            <div
                style="clear: both; height: 5px;"></div>
            <?php
        }// end while
        ?>
        <br />
        <img
            src="<?php echo W_ROOT; ?>/images/add_icon.jpg" border="0" />
        <a style="color: #00F; text-decoration: underline; cursor: pointer;"
           id="clicktoadd" onclick="$('#formaddnew').show();"><em>Add New Product</em></a>
        <?php
    } else {
        ?>
        <span id="id" style="color: #999;"><em>No Result Found !....</em></span>
        &nbsp;&nbsp;
        <img
            src="<?php echo W_ROOT; ?>/images/add_icon.jpg" border="0" />
        <a
            style="color: #00F; text-decoration: underline; cursor: pointer; width: 547px;"
            id="clicktoadd" onclick="$('#formaddnew').show();"><em>Add New Product</em></a>
        <br />
        <br />
        <br />
        <?php
    }
}

function displayexit() {
    $id = isset($_GET['id']) ? $_GET['id'] : '';
    $exist = 1;
    include(S_ROOT . '/admin/product/formaddexist.php');
    exit;
}

function display() {
    $id = $_GET['id'];
    $sql = "SELECT * FROM tblcategory WHERE parent_id = $id";
    $result = mysql_query($sql);
    ?>
    <br />
    <?php
    while ($row = dbFetchassoc($result)) {
        ?>
        <option value="<?php echo $row['id']; ?>"><?php echo $row['category_name']; ?></option>
        <?php
    }
}

function updatePrice() {
    $pro_id = $_POST['hidepid'];
    foreach ($pro_id as $value) {
        $price = $_POST['price' . $value];
        $sql_price = "UPDATE tblproduct_in_pharmacy SET price = '$price' WHERE pid = $value";
        mysql_query($sql_price);
    }
    header('Location: ' . W_ROOT . '/seller/editProductPrice.php?updatesuccess=1');
}

function publishSelected() {
    if (isset($_POST['id'])) {
        if (isset($_GET['publish']) && (int) $_GET['publish'] >= 0 && (int) $_GET['publish'] <= 1) {
            $publish = (int) $_GET['publish'];
        } else {
            header('Location: index.php');
            exit();
        }


        if (isset($_GET['pharm_id']) && (int) $_GET['pharm_id'] >= 0) {
            $phar_id = (int) $_GET['pharm_id'];
        }

        //Statement to get selected id
        $id = (is_array($_POST['id'])) ? implode(',', $_POST['id']) : $_POST['id'];

        //Statement to publish/unpublish selected id
        publishPro('tblproduct_in_pharmacy', $publish, $id, $phar_id);
    }

    header('Location: index.php?' . getAllGetParams(array('view', 'action', 'publish')));
    exit();
}

function deleteSelected() {
    if (isset($_POST['id'])) {
        //Statement to get selected id
        $id = (is_array($_POST['id'])) ? implode(',', $_POST['id']) : $_POST['id'];
        $selec_delet = "SELECT *FROM tblproduct AS pro INNER JOIN tblimage AS im ON pro.id=im.product_id WHERE product_id IN($id)";
        $run_query = mysql_query($selec_delet);
        //Statment to delete selected id
        $sql = "DELETE FROM tblproduct WHERE id IN ($id)";
        mysql_query($sql);
        $imagePath = '/product/images/';
        if (mysql_num_rows($run_query) > 0) {
            while ($rows = mysql_fetch_array($run_query)) {
                $product_image = $rows['images'];
                $product_thumbnail = $rows['thumbnail'];
                $product_original_img = $rows['original_img'];
                unlink(S_ROOT . $imagePath . $product_image);
                unlink(S_ROOT . $imagePath . $product_thumbnail);
                unlink(S_ROOT . $imagePath . $product_original_img);
            }
        }
    }
    header('Location: ' . $_SESSION['shop_return_url']);
}

function uploadPhoto($input, $uploadDir) {
    //$image     = $_FILES[$inputName];
    $image = $input;

    $imagePath = '';
    $thumbnailPath = '';
    // if a file is given
    if (trim($image['tmp_name']) != '') {

        $ext = substr(strrchr($image['name'], "."), 1); //$extensions[$image['type']];
        // generate a random new file name to avoid name conflict
        //$imagePath = $image['name'];
        $imagePath = md5(rand() * time()) . ".$ext";

        list($width, $height, $type, $attr) = getimagesize($image['tmp_name']);
        if (true && $width > 300) {
            $result = createThumbnail($image['tmp_name'], $uploadDir . $imagePath, 300);
            $imagePath = $result;
            applyWaterMark($uploadDir, $imagePath);
        } else {
            $result = move_uploaded_file($image['tmp_name'], $uploadDir . $imagePath);
            applyWaterMark($uploadDir, $imagePath);
        }

        if ($result) {
            // create thumbnail
            $thumbnailPath = md5(rand() * time()) . ".$ext";
            $size = getimagesize($uploadDir . $imagePath);
            if ($size[0] > 100) {
                $result = createThumbnail($uploadDir . $imagePath, $uploadDir . $thumbnailPath, 100);
                applyWaterMark($uploadDir, $thumbnailPath);
            } else {
                copy($uploadDir . $imagePath, $uploadDir . $thumbnailPath);
                $result = basename($uploadDir . $thumbnailPath);
                applyWaterMark($uploadDir, $result);
            }

            // create thumbnail failed, delete the image
            if (!$result) {
                unlink($uploadDir . $imagePath);
                $imagePath = $thumbnailPath = '';
            } else {
                $thumbnailPath = $result;
                applyWaterMark($uploadDir, $thumbnailPath);
            }
        } else {
            // the product cannot be upload / resized
            $imagePath = $thumbnailPath = '';
        }
    }
    applyWaterMark($uploadDir, $thumbnailPath);
    applyWaterMark($uploadDir, $imagePath);
    return array('image' => $imagePath, 'thumbnail' => $thumbnailPath);
}

function createThumbnail($srcFile, $destFile, $width, $quality = 100) {
    $thumbnail = '';

    if (file_exists($srcFile) && isset($destFile)) {
        $size = getimagesize($srcFile);
        $w = number_format($width, 0, ',', '');
        $h = floor($width);

        $thumbnail = copyImage($srcFile, $destFile, $w, $h, $quality);
    }
    return basename($thumbnail);
}

function copyImage($srcFile, $destFile, $w, $h, $quality = 100) {
    $tmpSrc = pathinfo(strtolower($srcFile));
    $tmpDest = pathinfo(strtolower($destFile));
    $size = getimagesize($srcFile);

    if ($tmpDest['extension'] == "gif" || $tmpDest['extension'] == "jpg") {
        $destFile = substr_replace($destFile, 'jpg', -3);
        $dest = imagecreatetruecolor($w, $h);
        imageantialias($dest, TRUE);
    } elseif ($tmpDest['extension'] == "png") {
        $dest = imagecreatetruecolor($w, $h);
        imageantialias($dest, TRUE);
    } else {
        return false;
    }

    switch ($size[2]) {
        case 1:       //GIF
            $src = imagecreatefromgif($srcFile);
            break;
        case 2:       //JPEG
            $src = imagecreatefromjpeg($srcFile);
            break;
        case 3:       //PNG
            $src = imagecreatefrompng($srcFile);
            break;
        default:
            return false;
            break;
    }

    imagecopyresampled($dest, $src, 0, 0, 0, 0, $w, $h, $size[0], $size[1]);

    switch ($size[2]) {
        case 1:
        case 2:
            imagejpeg($dest, $destFile, $quality);
            break;
        case 3:
            imagepng($dest, $destFile);
    }
    return $destFile;
}
?>
